package store;

import org.jdom.Element;
import exceptions.XmlException;

public class PortataBevanda extends Portata {
	int quantBevanda;
	Cibo bevanda;
	
	public PortataBevanda(int quant, Cibo bevanda) {
		this.quantBevanda = quant;
		this.bevanda = bevanda;
	}
	
	public int getQuantBevanda() {
		return quantBevanda;
	}
	
	public Cibo getBevanda() {
		return bevanda;
	}
	
	public Element toXml() {
		Element portata = new Element("portata_bevanda");
		portata.addContent(new Element("quantita_bevanda").setText(Integer.toString(quantBevanda)));
		portata.addContent(new Element("cibo").setText(bevanda.getNome()));
		return portata;
	}
	
	public static PortataBevanda fromXml(Element portata, boolean check) throws XmlException {
		int quant = Integer.parseInt(portata.getChildText("quantita_bevanda"));
		Cibo bevanda;
		if (check) {
			try {
				bevanda = Cibo.fromXml(TuttiCibi.getTuttiCibi().getCiboElement(portata.getChildText("cibo")));
			} catch (Exception e) {
				throw new XmlException(e);
			}
		} else bevanda = new Cibo(portata.getChildText("cibo"), null, null);
		PortataBevanda p = new PortataBevanda(quant, bevanda);
		
		return p;
	}
	
	@Override
	public String vis() {
		if (bevanda.getInfo().getUnitaRiferimento() != null && getQuantBevanda() != 0) {
			return quantBevanda + " " + bevanda.getInfo().getUnitaRiferimento().toStringShort() + " di " + bevanda;
		}
		return bevanda.toString();
	}
	
	@Override
	public String toString() {
		return vis();
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((bevanda == null) ? 0 : bevanda.hashCode());
		result = prime * result + quantBevanda;
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj) return true;
		if (obj == null) return false;
		if (getClass() != obj.getClass()) return false;
		PortataBevanda other = (PortataBevanda)obj;
		if (bevanda == null) {
			if (other.bevanda != null) return false;
		} else if (!bevanda.equals(other.bevanda)) return false;
		if (quantBevanda != other.quantBevanda) return false;
		return true;
	}
}
